package com.aisile.crowd_funding.system.shiro;

import com.aisile.crowd_funding.common.config.Constant;
import com.aisile.crowd_funding.common.utils.MD5Utils;
import com.aisile.crowd_funding.system.pojo.SysUser;
import com.aisile.crowd_funding.system.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    /**
     * 授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        String userName=token.getUsername();
        String password= new String(token.getPassword());
        //根据用户名 去数据库查询
        SysUser user = userService.findByUserName(userName);
        if(user==null){
            throw new UnknownAccountException();
        }
        if(!user.getPassword().equals(password)){
            //认证失败
            throw new AuthenticationException();
        }
        if(user.getStatus()== Constant.USER_STATUS){
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),getName());

        return info;
    }
}
